<?php
namespace modules\admin\service;

use idea\saf\sl\Service;
use idea\ap\Ap;
use idea\ap\Singleton;
use idea\ap\UserIdentity;
use helper\ErrorNo;
use helper\ErrorMsg;
use helper\Log;
use helper\Util;
use modules\admin\form;

/**
 * Admins class file
 * admins表服务类
 * @author 宋欢 <iphper@yeah.net>
 * @version $Id: Admins.php 1 2013-05-18 14:58:59Z huan.song $
 * @package modules.admin.service
 * @since 1.0
 */
class Admins extends Service
{
	/**
	 * 添加一条记录
	 * @param array $params
	 * @return array
	 */
	public function add(array $params = array())
	{
		$rules = $this->getForm()->getRules();
		$filter = Singleton::getInstance('idea\validator\Filter');
		if (!$filter->run($rules, $params, true)) {
			$errNo = ErrorNo::ERROR_ARGS_INSERT;
			$errMsg = ErrorMsg::ERROR_ARGS_INSERT;
			$errors = $filter->getErrors(true);
			Log::warning(sprintf(
				'%s attributes "%s", errors "%s"', $errMsg, serialize($params), serialize($errors)
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg,
				'errors' => $errors
			);
		}

		$dtNowTime = date('Y-m-d H:i:s');
		if (isset($params['admin_password'])) {
			$params['admin_password'] = md5($params['admin_password']);
		}

		$params['dt_registered'] = $dtNowTime;
		$params['ip_last_login'] = Ap::getRequest()->getClientIp();
		$params['dt_last_login'] = $dtNowTime;

		return $this->insert($params);
	}

	/**
	 * 更新一条记录
	 * @param integer $id
	 * @param array $params
	 * @return array
	 */
	public function edit($id , array $params = array())
	{
		$this->removeAttributes($params, array('admin_loginname'));
		if ($params['admin_password'] === '') {
			$this->removeAttributes($params, array('admin_password', 'admin_repassword'));
		}
		
		$rules = $this->getForm()->getRules();
		$filter = Singleton::getInstance('idea\validator\Filter');
		if (!$filter->run($rules, $params, false)) {
			$errNo = ErrorNo::ERROR_ARGS_UPDATE;
			$errMsg = ErrorMsg::ERROR_ARGS_UPDATE;
			$errors = $filter->getErrors(true);
			Log::warning(sprintf(
				'%s pk "%d", attributes "%s", errors "%s"', $errMsg, $id, serialize($params), serialize($errors)
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg,
				'errors' => $errors,
				'id' => $id
			);
		}
		
		if (isset($params['admin_password'])) {
			$params['admin_password'] = md5($params['admin_password']);
		}
		
		return $this->updateByPk($id, $params);
	}
	
	/**
	 * 更新是否激活的状态
	 * @param integer $id
	 * @param string $status
	 * @return array
	 */
	public function editStatus($id, $status = '')
	{
		$params = array(
			'user_status' => ($status === '') ? form\Admins::USER_STATUS_N : strtolower($status)
		);

		return $this->edit($id, $params);
	}
	
	/**
	 * 用户登录
	 * @param array $params
	 * @return array
	 */
	public function login(array $params = array())
	{
		$ret = $this->getIdByNameAndPwd($params);
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			return $ret;
		}
		
		$this->editLoginInfo($ret['id']);
		UserIdentity::registerID($ret['id']);
		$ret['err_msg'] = ErrorMsg::SUCCESS_LOGIN;
		return $ret;
	}
	
	/**
	 * 通过登录名和密码，查询一条记录
	 * @param array $params: admin_loginname、admin_password
	 * @return array
	 */
	public function getIdByNameAndPwd(array $params = array())
	{
		$loginname = isset($params['admin_loginname']) ? trim($params['admin_loginname']) : '';
		$password = isset($params['admin_password']) ? trim($params['admin_password']) : '';

		if ($loginname == '') {
			$errNo = ErrorNo::ERROR_LOGIN_FAILED_NAME_EMPTY;
			$errMsg = ErrorMsg::ERROR_LOGIN_FAILED_NAME_EMPTY;
			Log::warning(sprintf(
				'%s admin_loginname empty', $errMsg
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg
			);
		}
		
		if ($password == '') {
			$errNo = ErrorNo::ERROR_LOGIN_FAILED_PWD_EMPTY;
			$errMsg = ErrorMsg::ERROR_LOGIN_FAILED_PWD_EMPTY;
			Log::warning(sprintf(
				'%s admin_password empty', $errMsg
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg
			);
		}

		$ret = $this->countByAttributes(array(
			'admin_loginname' => $loginname,
		));
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			return $ret;
		}
		if ($ret['total'] <= 0) {
			$errNo = ErrorNo::ERROR_LOGIN_FAILED_NAME_NOT_EXISTS;
			$errMsg = ErrorMsg::ERROR_LOGIN_FAILED_NAME_NOT_EXISTS;
			Log::dbWarning(sprintf(
				'%s admin_loginname "%s"', $errMsg, $loginname
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg
			);
		}

		$attributes = array(
			'admin_loginname' => $loginname,
			'admin_password' => md5($password),
			'user_status' => form\Admins::USER_STATUS_Y,
		);

		$ret = $this->getPkByAttributes($attributes);
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			$errNo = ErrorNo::ERROR_LOGIN_FAILED_PWD_ERR;
			$errMsg = ErrorMsg::ERROR_LOGIN_FAILED_PWD_ERR;
			Log::dbWarning(sprintf(
				'%s admin_loginname "%s"', $errMsg, $loginname
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg
			);
		}

		$errNo = ErrorNo::SUCCESS_NUM;
		$errMsg = ErrorMsg::SUCCESS_SELECT;
		Log::dbNotice(sprintf(
			'%s admin_id "%d", admin_loginname "%s"', $errMsg, $ret['id'], $loginname
		), __METHOD__);

		return array(
			'err_no' => $errNo,
			'err_msg' => $errMsg,
			'id' => $ret['id']
		);
	}
	
	/**
	 * 获取所有激活状态的管理员信息
	 * @return array
	 */
	public function findAllByStatusY()
	{
		return parent::findAllByAttributes(array(
			'user_status' => form\Admins::USER_STATUS_Y,
		));
	}

	/**
	 * 通过管理员ID，获取管理员信息，不查询密码
	 * @param integer $value
	 * @return array
	 */
	public function findNoPwdByPk($value)
	{
		$ret = parent::findByPk($value);
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			return $ret;
		}

		unset($ret['data']['admin_password']);
		return $ret;
	}

	/**
	 * 通过管理员ID，获取管理组信息
	 * @param integer $value
	 * @return array
	 */
	public function getGroupsById($value)
	{
		$ret = parent::getByPk('group_id', $value);
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			return $ret;
		}

		$ret = Util::getService('AdminsGroups', 'admin')->findByPk($ret['group_id']);
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			return $ret;
		}

		$ret['admin_id'] = $value;
		return $ret;
	}

	/**
	 * 通过管理员ID，更新管理员登录信息
	 * @param integer $value
	 * @return array
	 */
	public function editLoginInfo($value)
	{
		$attributes = array(
			'ip_last_login' => Ap::getRequest()->getClientIp(),
			'dt_last_login' => date('Y-m-d H:i:s'),
		);

		return $this->updateByPk($value, $attributes);
	}
}
